import React, { useState, useEffect } from "react";
import Popup from "@components";

import { getUpdateInfo } from "@utils";

const UpdateComponent = () => {
  const [downloading, setDownloading] = useState(false);
  const [updateInfo, setUpdateInfo] = useState({
    update: false,
    data: {
      update: {
        message: false,
        downloadUrl: false,
        moreUrl: false,
      },
    },
  });

  const { update, data: updateData } = updateInfo;

  useEffect(() => {
    getUpdateInfo(function ({ update_info }) {
      if (!update_info) return;
      console.log("更新日志信息:", update_info);
      setUpdateInfo(update_info);
    });
  }, []);

  function handleDownload() {
    setDownloading(true);

    const options = {
      url: updateData.update.downloadUrl,
      filename: `ShirKhan-Chrome-Plugin-${updateData.version.cur}.zip`,
      saveAs: true,
    };

    chrome.downloads.download(options, () => {
      setDownloading(false);
    });
  }

  function handleDownloadCrx() {
    setDownloading(true);

    const options = {
      url: updateData.update.downloadCrxUrl,
      filename: `ShirKhan-Chrome-Plugin-${updateData.version.cur}.crx`,
      saveAs: true,
    };

    chrome.downloads.download(options, () => {
      setDownloading(false);
    });
  }

  function handleMore() {
    chrome.tabs.create({
      url: updateData.update.moreUrl,
    });
  }

  return update ? (
    <Popup.Update
      updateMessage={updateData.update.message}
      moreUrl={updateData.update.moreUrl}
      downloadUrl={updateData.update.downloadUrl}
      downloadCrxUrl={updateData.update.downloadCrxUrl}
      onMoreClick={handleMore}
      onDownloadClick={handleDownload}
      onDownloadCrxClick={handleDownloadCrx}
      downloading={downloading}
    />
  ) : (
    ""
  );
};

export default UpdateComponent;
